package servlet;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Section;

import org.json.JSONArray;
import org.json.JSONObject;

import dao.ObjectDAO;


/**
 * Servlet implementation class sectionData
 */
public class sectionData extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ObjectDAO oDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public sectionData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		Writer out = response.getWriter();
		String jsonString = "";
		oDao = new ObjectDAO();
		
		/**
		 * cast data from database into json to present on Jqgrid in view
		 */
		
		try {
			if(!session.isNew()) {
				JSONObject o = new JSONObject();
				
				for(int i =1; i <=2; i++) {
					JSONArray cellArray = new JSONArray();
					ArrayList<Section> list = oDao.getSectionByCategory(i);
					
					for(Section s: list) {
						JSONObject cellObj = new JSONObject();
						cellObj.put("id", s.getSectionId());
						cellObj.put("name", s.getSectionName());
						cellArray.put(cellObj);
					}		
					o.put(Integer.toString(i),cellArray);
					
				}
				jsonString = o.toString();

				out.write(jsonString);
				out.flush();
				
			}
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
